package com.cloudpivot.receivales.contract.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.contract.domain.NormalReturn;
import com.cloudpivot.receivales.contract.domain.bpm.BpmContractMain;
import com.cloudpivot.receivales.contract.domain.oa.OAContract;
import com.cloudpivot.receivales.contract.service.http.HttpAPIServiceForCrm;
import com.cloudpivot.receivales.contract.service.impl.*;
import com.cloudpivot.receivales.contract.util.CompanyEnum;
import com.cloudpivot.receivales.util.DingMessageUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取OA接口
 */
@Controller
@Slf4j
@RequestMapping("/contract")
public class ReceiveContractController {

    @Autowired
    private DingMessageUtil dingMessageUtil;

    @Autowired
    private HttpAPIServiceForCrm httpAPIServiceForCrm;

    @Autowired
    private OAContractServiceImpl oaService;

    @Autowired
    private CrmContractServiceImpl crmContractService;

    @Autowired
    private ErpContractServiceImpl erpContractService;

    @Autowired
    private ErpMiddleServiceImpl erpMiddleService;

    @Autowired
    private OASreviceImpl oaSrevice;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${myprops.cpurl}")
    private String CPURL;

    /**
     * 获取OA合同 receiveContract
     *
     * @return
     */
    @PostMapping(value = "receiveContract")
    @ResponseBody
    public NormalReturn receiveContract(@Validated @RequestBody OAContract oaContract) {
        try {
            log.info("获取到的json:{}", objectMapper.writeValueAsString(oaContract));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        Map<String, String> resMap = new HashMap<>();
        NormalReturn normalReturn = oaService.getOAPOJO(oaContract);
        if (normalReturn.getCode() == -1) {
            //出现异常，直接返回
            return normalReturn;
        }
        String strContractID = normalReturn.getMsg();
        resMap.put("erpContractId", strContractID);
        log.info("strContractID:(推送ERP生成的ID)" + strContractID);
        String crmContractID = "";
        //推送CRM (先暂停 替换字符串)
//        oaContract.setXitongff(oaContract.getXitongff().replace("CRM",""));
        //特殊CRM 推送
        if (oaContract.getXitongff().contains("CRMBPM")) {
            crmContractID = crmContractService.addContractByEntity(strContractID, oaContract,"2");
            resMap.put("crmContractId", crmContractID);
            //插入U8中间表 防止同步
            if (resMap.containsKey("crmContractId") && resMap.containsKey("erpContractId")) {
                erpMiddleService.addU8MiddleResult(resMap.get("erpContractId"), resMap.get("crmContractId"));
            }
        }

        //其他系统.....

        //推送中台
        Map<String, String> cpmodel = new HashMap<>();
        cpmodel.put("erpid", strContractID);
        cpmodel.put("crmid", crmContractID);
        String cpurl = String.format("%s%s", CPURL, "/api/outservice/addcontract");
        String cpid = "";
        try {
            cpid = httpAPIServiceForCrm.doPost(cpurl, objectMapper.writeValueAsString(cpmodel), null);
            resMap.put("cpId", cpid);
        } catch (Exception e) {
            e.printStackTrace();
        }

        dingMessageUtil.pushMessage(null,"推送合同成功" + JSONObject.toJSONString(resMap));
        return new NormalReturn(1, "推送合同成功", "", resMap);
    }

    /**
     * 推送CRM U8(可选)合同中间件服务接口
     * 1.推送CRM(合同编码直接使用流程编码)
     * 2.推送U8中间表记录
     *
     * @return
     */
    @PostMapping(value = "receiveContractV3")
    @ResponseBody
    public NormalReturn receiveContractV3(@Validated @RequestBody BpmContractMain bpmContractMain) {
        log.info("获取到的json:{}", JSONObject.toJSONString(bpmContractMain));

        //v3BPM 增加转换
        OAContract oaContract=JSONObject.parseObject(JSONObject.toJSONString(bpmContractMain), OAContract.class);
        log.info("获取到转换为OAContract的对象打印:{}", JSONObject.toJSONString(bpmContractMain));
        Map<String, String> resMap = new HashMap<>();
        NormalReturn normalReturn = oaService.getOAPOJO(oaContract);
        if (normalReturn.getCode() == -1) {
            //出现异常，直接返回
            return normalReturn;
        }
        String strContractID = normalReturn.getMsg();
        resMap.put("erpContractId", strContractID);
        log.info("strContractID:(推送ERP生成的ID)" + strContractID);
        String crmContractID = "";
        //推送CRM (先暂停 替换字符串)
//        oaContract.setXitongff(oaContract.getXitongff().replace("CRM",""));
        //特殊CRM 推送
        if (oaContract.getXitongff().contains("CRMBPM")) {
            log.info("推送crm合同");
            crmContractID = crmContractService.addContractByEntity(strContractID, oaContract,"3");
            resMap.put("crmContractId", crmContractID);
            //插入U8中间表 防止同步
            if (resMap.containsKey("crmContractId") && resMap.containsKey("erpContractId")) {
                erpMiddleService.addU8MiddleResult(resMap.get("erpContractId"), resMap.get("crmContractId"));
            }
        }
        //其他系统.....

        //直接返回结果
        //合同同步记录器
        Map<String, String> cpmodel = new HashMap<>();
        cpmodel.put("erpid", strContractID);
        cpmodel.put("crmid", crmContractID);
        String cpurl = String.format("%s%s", CPURL, "/api/outservice/addcontract");
        String cpid = "";
        try {
            cpid = httpAPIServiceForCrm.doPost(cpurl, objectMapper.writeValueAsString(cpmodel), null);
            resMap.put("cpId", cpid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        dingMessageUtil.pushMessage(null, "推送合同成功(只推送CRM)" + JSONObject.toJSONString(resMap));
        return new NormalReturn(1, "推送合同成功", "", resMap);
    }

    /**
     * 为V3报价准备的全新的合同推送接口
     */

    /**
     * 更新存放位置
     *
     * @return
     */
    @ResponseBody
    @PostMapping(value = "upCunFang")
    public String updateCunfangwz(@RequestParam(value = "cfwz") String cfwz, @RequestParam(value = "ID") String strContractID, @RequestParam(value = "guid") String guid) {

        log.info("获取到的存放位置:{}", cfwz);

        if (StringUtils.isBlank(cfwz) || StringUtils.isBlank(strContractID) || StringUtils.isBlank(guid)) {
            return "入参异常，请检查";
        }
        /**
         * erp更新
         */
        erpContractService.updateCFWZ(cfwz, strContractID);
        /**
         * crm更新
         */
        crmContractService.updateCrmCFWZ(cfwz, guid);
        log.info("更新存放位置成功");
        return "更新存放位置成功";
    }

    @PostMapping("/contractResultPush")
    @ResponseBody
    /**
     * 接收合同信息
     * todo:接受对象；不要用json，如果要用用fastjson，定义好对象，不要直接用json;常量放到yml里面
     */
    public void contractResultPush(@RequestBody Map<String, Object> map) {
        if (map.isEmpty()) {
            log.info("入参异常，请检查");
        } else {
            log.info("接收到的合同用章内容---->{}", map);
            JSONObject json = new JSONObject();
            json.put("座位号", map.get("zuoweih"));
            json.put("合同编号", map.get("liuchengbh"));
            json.put("申请日期", map.get("shenqingrq"));
            json.put("文件名称", map.get("wenjianmc"));
            json.put("合同有效期", map.get("hetongsj"));
            json.put("我方公司名称", CompanyEnum.getChineseNameByKey(map.get("yongyinggs").toString()));
            json.put("对方公司名称", map.get("gongyingsmc"));
            json.put("份数", map.get("yongyinsl"));
            json.put("合同金额", map.get("hetongje"));
            json.put("附件", map.get("hetonggdsc"));
            json.put("是否有原件", map.get("original_copy"));
            json.put("归档日期", map.get("filing_date"));
            oaSrevice.pushContract(json);
        }
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public NormalReturn exceptionHandler(MethodArgumentNotValidException e) {
        NormalReturn resultJson = new NormalReturn(-1, "error");
        resultJson.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return resultJson;
    }
}
